/*
 * @lc app=leetcode.cn id=609 lang=cpp
 *
 * [609] 在系统中查找重复文件
 */
#include "include.h"
// @lc code=start
class Solution {
public:
    vector<vector<string>> findDuplicate(vector<string>& paths) {
        vector<vector<string>> res;

        for (auto& path : paths){
            parseDirectory(path);
        }

        for (auto& pair : hashTable_){
            if (pair.second.size()>1){
                res.push_back(pair.second);
            }
        }

        return res;
    }
private:
    std::unordered_map<std::string, vector<std::string>> hashTable_;
    void parseDirectory(std::string& path){
        auto splits = stringSplit(path, ' ');
        std::string directory = splits[0];
        for (int i=1;i<splits.size();i++){
            int cut = splits[i].find('(');
            std::string fileName = splits[i].substr(0, cut);
            std::string fileContent = splits[i].substr(cut+1, splits[i].size()-cut-2);
            auto iter = hashTable_.find(fileContent);
            std::string fullPath = directory + '/' + fileName;

            if (iter == hashTable_.end()){
                hashTable_.emplace(fileContent, vector<string>(1, fullPath));
            } else{
                iter->second.push_back(fullPath);
            }
        }
    }
    std::vector<std::string> stringSplit(const std::string& str, char delim) {
    std::size_t previous = 0;
    std::size_t current = str.find(delim);
    std::vector<std::string> elems;
    while (current != std::string::npos) {
        if (current > previous) {
            elems.push_back(str.substr(previous, current - previous));
        }
        previous = current + 1;
        current = str.find(delim, previous);
    }
    if (previous != str.size()) {
        elems.push_back(str.substr(previous));
    }
    return elems;
}
};
// @lc code=end

